package com.lxq.live.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e)
            throws IOException {
        System.out.println(e.getMessage());
//        System.out.println("onAuthenticationFailure");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode echo = mapper.createObjectNode();
        echo.put("code", false);
        echo.put("result", "登录失败");
        echo.put("exception", e.getMessage());
        httpServletResponse.getWriter().write(echo.toString());
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }
}
